package com.example.demoexample.net;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.example.demoexample.Constant;
import com.example.demoexample.model.BaseDto;
import com.example.demoexample.utils.RxJavaUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;

public class NetworkWrapper {
    private static final String TAG = "NetworkWrapper";
    private static final int DEFAULT_TIMEOUT = 15;

    private  MyService myService;
    private Retrofit retrofit;
    private Observable observable;
    //构造方法私有
    private NetworkWrapper() {
        //创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Constant.BIPS_Server)
                .build();
        myService = retrofit.create(MyService.class);
    }

    //在访问NetworkWrapper时创建单例
    private static class SingletonHolder{
        private static final NetworkWrapper INSTANCE = new NetworkWrapper();
    }
    //获取单例
    public static NetworkWrapper getInstance(){
        return SingletonHolder.INSTANCE;
    }

    private static Map<String, Object> objectToMap(Object obj){
        if(obj == null){
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject;
        String jsonString = JSON.toJSONString(obj);
        Log.d(TAG,"objectToMap:"+jsonString);
        try {
//            jsonObject = new JSONObject(gson.toJson(obj));
            jsonObject = new JSONObject(jsonString);
            Iterator keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String value;
                try {
                    value = jsonObject.get(key).toString();
                    map.put(key,value);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 测试
     */
    public Observable<BaseDto> login(String loginName, String password) {
        observable = myService
                .login("", "");
        return observable.compose(RxJavaUtil.applySchedulers());
    }
}
